
$(function(){
    //入口函数
    //页面数据初始化
    webInit();
    function webInit(){
        $("b#allmoney").html("¥0");
        $("i#kinds").html("0");
        $("i#preall").html("0");
    }
    
    //判断当前是否有用户登录

    if($.cookie("spInfor")){
        var currentUser = JSON.parse($.cookie("spInfor")).username;
        console.log(currentUser);
        //获取到当前用户的信息
        $(".overTop_left>#login").remove();
        $(".overTop_left>#regist").remove();
        var userSpan = document.createElement("span");
        var exitA = document.createElement("a");
        userSpan.innerHTML = currentUser;
        exitA.innerHTML = "退出";
        $(".overTop_left").append($(userSpan)).append($(exitA));
        $(exitA).on("click",function(){
            $.removeCookie("spInfor");
            window.location.reload();
        })

        if($.cookie("goodsses")){
            console.log(JSON.parse($.cookie("goodsses")));
            //console.log(currentUser);
            var getori = {
                "url":"../hz_1706/spUser/version1/getcar.php",
                "data":{"phonenumber":currentUser},
                "dataType":"json",
                "type":"post",
                "success":function(oriData){
                    //将数据改变后存入
                    console.log(oriData);
                    if(!oriData.status){
                        // oriData.status=2时用户的购物车为空
                        //非空状态
                        //console.log(oriData.status);--undefined
                        JSON.parse($.cookie("goodsses")).forEach(function(eleck,indexck){
                            //ele--{serial: "dis02", sum: "6"}
                            var tpr = 0;
                            oriData.forEach(function(ele,index){
                                if(ele.serial==eleck.serial){
                                    //cookie中的该商品用户已经加入了自己的购物车，就让件数相加
                                    ele.sum=parseInt(ele.sum)+parseInt(eleck.sum);
                                    return;
                                }

                                tpr++;
                                console.log(tpr);
                                if(tpr==oriData.length){
                                    //cookie中该商品用户还没有存入自己的购物车，就将该商品的的信息和件数push进用户的购物车数组
                                    oriData.push(eleck);
                                }

                            })
                        })
                    }else{
                        //空购物车状态
                        oriData=JSON.parse($.cookie("goodsses"));
                    }

                    // console.log(oriData);---此时的oriData已经是改变过后的数据
                    //再次调用ajax将新的数据存入数据库
                    console.log(oriData);
                    var getcur = {
                        url:"../hz_1706/spUser/version1/changecar.php",
                        data:{"phonenumber":currentUser,"cardata":oriData},
                        type:"post",
                        dataType:"json",
                        success:function(curData){
                            if(curData.status==1){
                                //修改成功
                                $.removeCookie("goodsses");
                                loadWeb();
                                $("#partdel").on("click",partDel);
                            }
                        }
                    }
                    $.ajax(getcur);
                }
            }
            $.ajax(getori);

        }else{
            loadWeb();
            $("#partdel").on("click",partDel);
        }

    }else{
        //未获取到用户信息
        //查询cookie中的购物车
        if($.cookie("goodsses")){
            var eveCalc = 0;
            var len=0;
            var preall = 0;
            JSON.parse($.cookie("goodsses")).forEach(function(ele,index){
                // console.log(ele);
                var pregoods = {
                    url:"../json/detail_goodsInfor.json",
                        success:function(res){
                           console.log(res.goodsses[ele.serial]);
                            console.log(ele);
                            var goLi = document.createElement("li");
                            //根据商品的sale属性决定是自营还是全球购
                            if(res.goodsses[ele.serial].sale){
                                goLi.className = "goods_g"
                            }else{
                                goLi.className = "goods_s"
                            }
                            $("#goods>ol").append(goLi);
                            goLi.innerHTML="<div class='select'><input type='checkbox'/></div><div class='goodsInfor'><img src='"+res.goodsses[ele.serial].imgSrc_s[0]+"' alt='"+res.goodsses[ele.serial].name+"'><span>"+res.goodsses[ele.serial].name+"</span></div><div class='goodsCode'> <span>"+res.goodsses[ele.serial].number+"</span></div><div class='goodsPrice'> <span>"+res.goodsses[ele.serial].price+"</span> </div><div class='goodsSave'> <span>有库存</span></div><div class='goodsPay'><span>否</span></div><div class='goodsSum'> <button class='subtra'>-</button><input type='text' name='prenum' class='prenum' value='"+ele.sum+"'/> <button class='plus'>+</button> </div> <div class='goodsCalc'> <span>¥999.00</span> </div> <div class='goodsOpera'> <span>收藏</span><br> <span class='delbt'>删除</span></div>";
                            var preprice = Number($(goLi).children("div.goodsPrice").children("span").html().split("¥")[1]);
                            eveCalc+=preprice*ele.sum;
                            goLi.setAttribute("mts",ele.serial);
                            goLi.setAttribute("gds",ele.sum);
                            $(goLi).children("div.goodsCalc").children("span").html("¥"+preprice*ele.sum);
                            preall+=parseInt(ele.sum);
                            len++;

                            if(JSON.parse($.cookie("goodsses")).length==len){
                                //说明动态li创建完毕
                                renew(eveCalc,preall,len);
                            }
                        }
                }
                $.ajax(pregoods);
            })
        }
        $("#partdel").on("click",partDel);
    }

    function loadWeb(){
        console.log(currentUser);
        var togetCar = {
            url:"../hz_1706/spUser/version1/getcar.php",
            dataType:"json",
            type:"post",
            data:{"phonenumber":currentUser},
            success:function(dataCar){
                console.log(dataCar);
                var eveCalc = 0;
                var len=0;
                var preall = 0
                if(!dataCar.status){
                    dataCar.forEach(function(ele,index){
                        //console.log(ele, index);
                        //bg
                        var pregoods = {
                            url:"../json/detail_goodsInfor.json",
                            success:function(res){
                                //res==goodsses:{dis01:{...},dis02:{...}}
                                //dataCar==[{…}, {…}]0: {serial: "dis01", sum: 11}1: {serial: "dis02", sum: 9}

                                // console.log(res);
                                // console.log(dataCar);
                                //console.log(ele);
                                var goLi = document.createElement("li");
                                //根据商品的sale属性决定是自营还是全球购
                                if(res.goodsses[ele.serial].sale){
                                    goLi.className = "goods_g"
                                }else{
                                    goLi.className = "goods_s"
                                }
                                $("#goods>ol").append(goLi);
                                goLi.innerHTML="<div class='select'><input type='checkbox'/></div><div class='goodsInfor'><img src='"+res.goodsses[ele.serial].imgSrc_s[0]+"' alt='"+res.goodsses[ele.serial].name+"'><span>"+res.goodsses[ele.serial].name+"</span></div><div class='goodsCode'> <span>"+res.goodsses[ele.serial].number+"</span></div><div class='goodsPrice'> <span>"+res.goodsses[ele.serial].price+"</span> </div><div class='goodsSave'> <span>有库存</span></div><div class='goodsPay'><span>否</span></div><div class='goodsSum'> <button class='subtra'>-</button><input type='text' name='prenum' class='prenum' value='"+ele.sum+"'/> <button class='plus'>+</button> </div> <div class='goodsCalc'> <span>¥999.00</span> </div> <div class='goodsOpera'> <span>收藏</span><br> <span class='delbt'>删除</span></div>";
                                var preprice = Number($(goLi).children("div.goodsPrice").children("span").html().split("¥")[1]);
                                eveCalc+=preprice*ele.sum;
                                goLi.setAttribute("mts",ele.serial);
                                goLi.setAttribute("gds",ele.sum);

                                $(goLi).children("div.goodsCalc").children("span").html("¥"+preprice*ele.sum);
                                preall+=parseInt(ele.sum);
                                len++;
                                // console.log(eveCalc);
                                if(dataCar.length==len){
                                    //说明动态li创建完毕
                                    renew(eveCalc,preall,len);
                                }
                            }
                        }
                        $.ajax(pregoods);
                        //end
                    })
                }
            }
        }
        $.ajax(togetCar);
    }



    function renew(eveCalc,preall,len){
        $("#allmoney").html("¥"+eveCalc);
        $("#kinds").html(len);
        $("#preall").html(preall);
        $(".selall").on("click",function(){
            $("#goods").find("input[type=checkbox]").prop("checked",this.checked);
        })
        //改变件数
        $(".plus").on("click",function(){
            $(this).parents("div.goodsSum").children("input.prenum").val(parseInt($(this).parents("div.goodsSum").children("input.prenum").val())+1);
            console.log($(this).parents("div.goodsSum").children("input.prenum").val());
            changeData(this);

        })
        $(".subtra").on("click",function(){
            $(this).parents("div.goodsSum").children("input.prenum").val(parseInt($(this).parents("div.goodsSum").children("input.prenum").val())-1);
            if($(this).parents("div.goodsSum").children("input.prenum").val()<=0){
                $(this).parents("div.goodsSum").children("input.prenum").val(0);
            }
            changeData(this);

        })
        //删除数据
        $(".delbt").on("click",function(){
            console.log(this);
            $(this).parents("li").remove();
            delData(this);
        })
    }


    function changeData(ele){

        var newData=[];

        $("#goods ol>li").each(function(index,ele){
            var obj={};
            ele.setAttribute("gds",$(ele).find("input.prenum").val());
            obj.serial = ele.getAttribute("mts");
            obj.sum = ele.getAttribute("gds");
            console.log(obj);
            newData.push(obj);
        })
        //操作页面总计
        var kinds = 0;
        var amount = 0;
        var allgds = 0;
        $("#goods ol>li").each(function(index,ele){
            kinds++;
            allgds+=parseInt(ele.getAttribute("gds"));
            amount += parseInt($(ele).children("div.goodsPrice").html().split("¥")[1])*parseInt(ele.getAttribute("gds"));
        })
        $("#allmoney").html("¥"+amount);
        $("#kinds").html(kinds);
        $("#preall").html(allgds);
        var prepri = parseInt($(ele).parents("li").find("div.goodsPrice").children("span").html().split("¥")[1]);
        var gs = parseInt($(ele).parents("li").find("div.goodsSum").children("input[type=text]").val());
        $(ele).parents("li").find("div.goodsCalc").children("span").html("¥"+prepri*gs);
        console.log(newData);
        //操作数据库
        if(currentUser){
            //有用户登录的情况
            console.log(currentUser);
            var newdataCar = {
                url:"../hz_1706/spUser/version1/changecar.php",
                data:{"cardata":newData,"phonenumber":currentUser},
                type:"post",
                dataType:"json",
                success:function(res){
                    console.log(res);
                }
            }
            $.ajax(newdataCar)
        }
        else{
            //没有用户登录的情况，删除cookie中数据
            console.log(newData);
            $.cookie("goodsses",JSON.stringify(newData),{expires:20});




        }
    }

    function delData(ele){
        var kinds = 0;
        var amount = 0;
        var allgds = 0;
        $("#goods ol>li").each(function(index,ele){
            kinds++;
            allgds+=parseInt(ele.getAttribute("gds"));
            amount += parseInt($(ele).children("div.goodsPrice").html().split("¥")[1])*parseInt(ele.getAttribute("gds"));
        })
        $("#allmoney").html("¥"+amount);
        $("#kinds").html(kinds);
        $("#preall").html(allgds);

        var newData=[];
        $("#goods ol>li").each(function(index,ele){
            var obj={};
            obj.serial = ele.getAttribute("mts");
            obj.sum = ele.getAttribute("gds");
            newData.push(obj);
        })
        console.log(newData);
        if(currentUser){
            //有用户登录的情况
            console.log(currentUser);
            var newdataCar = {
                url:"../hz_1706/spUser/version1/changecar.php",
                data:{"cardata":newData,"phonenumber":currentUser},
                type:"post",
                dataType:"json",
                success:function(res){
                    console.log(res);
                }
            }
            $.ajax(newdataCar)
        }
        else{
            //没有用户登录的情况，删除cookie中数据
            $.cookie("goodsses",JSON.stringify(newData),{expires:20});
        }
    }
    function partDel(){
        $("#goods ol>li").each(function(index,ele){
            if($(ele).children("div.select").children("input[type=checkbox]")[0].checked){
                $(ele).remove();
            }
        })
        delData();


    }

    // $("")

})
